package com.haois.component.util;



import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

/**
 * description
 *
 * @author RuiHaoZ on GCU
 * @date 2017/3/17 9:18
 */
public class GetAddByIp {
    private static String baiduIpApiUrl = "http://api.map.baidu.com/location/ip?ak=8aOhOuDbIjOa1HUsaZt1aWQwsrVeoDu2&ip=";

    public static String getAddressByIP(String strIP) {
        try {

            URL url = new URL(baiduIpApiUrl + strIP);
            URLConnection conn = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line = null;
            StringBuffer result = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            reader.close();
            String ipAddr = result.toString();
            try {
                JSONObject obj1 = JSONObject.fromObject(ipAddr);
                if ("0".equals(obj1.get("status").toString())) {
                    JSONObject obj2 =JSONObject.fromObject(obj1.get("content"));
                    JSONObject obj3 = JSONObject.fromObject(obj1.get("address_detail"));

                    String city = obj3.get("city").toString();
                    String province = obj3.get("province").toString();

                    String address = obj2.get("address").toString();

                    return address;
                } else {
                    return "读取失败";
                }
            } catch (JSONException e) {
                e.printStackTrace();
                return "读取失败";
            }
        } catch (IOException e) {
            return "读取失败";
        }
    }

    public static String transferByIp(String strIP) {
        try {
            URL url = new URL(baiduIpApiUrl + strIP);
            URLConnection conn = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line = null;
            StringBuffer result = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            reader.close();
            JSONObject obj1 = JSONObject.fromObject(result);
            return obj1.toString();
        } catch (Exception e) {
            return "读取失败";
        }
    }
}
